package eu.telecom_bretagne.RECRUT.service;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import java.util.List;
import java.util.Set;

import eu.telecom_bretagne.RECRUT.data.dao.ArchiveDAO;
import eu.telecom_bretagne.RECRUT.data.dao.DossierCandidatureDAO;
import eu.telecom_bretagne.RECRUT.data.dao.EmployeDAO;
import eu.telecom_bretagne.RECRUT.data.dao.OffreDAO;
import eu.telecom_bretagne.RECRUT.data.model.Archive;
import eu.telecom_bretagne.RECRUT.data.model.DossierCandidature;
import eu.telecom_bretagne.RECRUT.data.model.Employe;
import eu.telecom_bretagne.RECRUT.data.model.Offre;

/**
 * Session Bean implementation class ServiceEmploye
 */
@Stateless
@LocalBean
public class ServiceEmploye implements IServiceEmploye {

	@EJB
	EmployeDAO employeDAO;
	@EJB
	ArchiveDAO archiveDAO;
	@EJB
	OffreDAO offreDAO;
	@EJB
	DossierCandidatureDAO dossierCandidatureDAO;

	/**
	 * Default constructor.
	 */
	public ServiceEmploye() {
	}

	@Override
	public List<Employe> listeEmployes() {

		return employeDAO.findAll();
	}

	@Override
	public Employe lireEmploye(int id) {

		return employeDAO.findById(id);
	}

	@Override
	public void modifierEmploye(int id, String nouveauNom,
			String nouveauPrenom, String nouveauType, String nouveauDepartement) {

		Employe employe = lireEmploye(id);
		employe.setNomEmploye(nouveauNom);
		employe.setPrenomEmploye(nouveauPrenom);
		employe.setTypeEmploye(nouveauType);
		employe.setDepartement(nouveauDepartement);
	}

	@Override
	public Employe creerEmploye(String nouveauNom, String nouveauPrenom,
			String type, String departement) {

		Employe employe = new Employe();
		employe.setNomEmploye(nouveauNom);
		employe.setPrenomEmploye(nouveauPrenom);
		employe.setTypeEmploye(type);
		employe.setDepartement(departement);

		employeDAO.create(employe);

		return employe;
	}

	@Override
	public void supprimerEmploye(int id) {

		Employe employe = employeDAO.findById(id);
		
		Set<Archive> archiveEmployes = employe.getArchives();

		for (Archive archiveEmploye : archiveEmployes) {
			archiveEmploye.getEmploye().removeArchive(archiveEmploye);
			archiveDAO.update(archiveEmploye);
		}

		Set<Offre> offreEmployes = employe.getOffres();

		for (Offre offreEmploye : offreEmployes) {
			offreEmploye.getEmploye().removeOffre(offreEmploye);
			offreDAO.update(offreEmploye);
		}

		Set<DossierCandidature> dossierEmployes = employe
				.getDossierCandidatures();

		for (DossierCandidature dossierEmploye : dossierEmployes) {
			dossierEmploye.getEmployes().removeAll(dossierEmployes);
			dossierCandidatureDAO.update(dossierEmploye);
		}

		employeDAO.delete(employe);
	}
}
